package com.haven123.cloudapp.webbase.web;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Tony_Du on 2017/12/27.
 */
@Configuration
public class ArgumentConvertConfig {

    /***
     * 日期自动转换
     * @return
     */
    @Bean
    public Converter<String, Date> stringDateConverter() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                if (StringUtils.isBlank(source)) {
                    return null;
                }
                source = source.trim();
                try {
                    if (source.contains("-")) {
                        SimpleDateFormat formatter;
                        if (source.contains(":")) {
                            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        } else {
                            formatter = new SimpleDateFormat("yyyy-MM-dd");
                        }
                        return formatter.parse(source);
                    } else if (source.matches("^\\d+$")) {
                        Long lDate = new Long(source);
                        return new Date(lDate);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(String.format("parser %s to Date fail", source));
                }
                throw new RuntimeException(String.format("parser %s to Date fail", source));
            }
        };
    }

}
